package cn.loioi.websocket.pool;

import java.io.IOException;
import java.io.Serializable;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :连接对象 <br>
 * @file_name :Connecttion.java <br>
 * @author :yyzh <br>
 * @创建时间 :2016年2月3日 下午1:47:57
 */
public class Connecttion implements Serializable {
	private static final long serialVersionUID = 2218589019061360684L;
	private String account;
	private WebSocketSession ws;

	public Connecttion(String account) {
		this.account = account;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public WebSocketSession getWs() {
		return ws;
	}

	public void setWs(WebSocketSession ws) {
		this.ws = ws;
	}

	public String getRemoteAddress() {
		return this.ws.getRemoteAddress().toString();
	}

	/**
	 * 发送消息
	 * @param obj
	 * @throws IOException
	 */
	public void send(Object obj) throws IOException {
		WebSocketMessage<?> message = null;
		if (obj instanceof WebSocketMessage) {
			message = (WebSocketMessage<?>) obj;
		} else if (obj instanceof Number) {
			message = new TextMessage(String.valueOf(obj));
		} else if (obj instanceof String) {
			message = new TextMessage((String) obj);
		} else if (obj instanceof JSON) {
			message = new TextMessage(((JSON) obj).toJSONString());
		} else if (obj != null) {
			message = new TextMessage(JSON.toJSONString(obj));
		} else {
			message = new TextMessage("{}");
		}
		this.ws.sendMessage(message);
	}
}
